/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojos.Projects;
import pojos.Employees;
import pojos.TimeLog;

/**
 *
 * @author A7med Kotb
 */
public class TimeLogJpaController implements Serializable {

    public TimeLogJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(TimeLog timeLog) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Projects project = timeLog.getProject();
            if (project != null) {
                project = em.getReference(project.getClass(), project.getProId());
                timeLog.setProject(project);
            }
            Employees emplyee = timeLog.getEmplyee();
            if (emplyee != null) {
                emplyee = em.getReference(emplyee.getClass(), emplyee.getEmpId());
                timeLog.setEmplyee(emplyee);
            }
            Employees createdBy = timeLog.getCreatedBy();
            if (createdBy != null) {
                createdBy = em.getReference(createdBy.getClass(), createdBy.getEmpId());
                timeLog.setCreatedBy(createdBy);
            }
            em.persist(timeLog);
            if (project != null) {
                project.getTimeLogCollection().add(timeLog);
                project = em.merge(project);
            }
            if (emplyee != null) {
                emplyee.getTimeLogCollection().add(timeLog);
                emplyee = em.merge(emplyee);
            }
            if (createdBy != null) {
                createdBy.getTimeLogCollection().add(timeLog);
                createdBy = em.merge(createdBy);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(TimeLog timeLog) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            TimeLog persistentTimeLog = em.find(TimeLog.class, timeLog.getTlId());
            Projects projectOld = persistentTimeLog.getProject();
            Projects projectNew = timeLog.getProject();
            Employees emplyeeOld = persistentTimeLog.getEmplyee();
            Employees emplyeeNew = timeLog.getEmplyee();
            Employees createdByOld = persistentTimeLog.getCreatedBy();
            Employees createdByNew = timeLog.getCreatedBy();
            if (projectNew != null) {
                projectNew = em.getReference(projectNew.getClass(), projectNew.getProId());
                timeLog.setProject(projectNew);
            }
            if (emplyeeNew != null) {
                emplyeeNew = em.getReference(emplyeeNew.getClass(), emplyeeNew.getEmpId());
                timeLog.setEmplyee(emplyeeNew);
            }
            if (createdByNew != null) {
                createdByNew = em.getReference(createdByNew.getClass(), createdByNew.getEmpId());
                timeLog.setCreatedBy(createdByNew);
            }
            timeLog = em.merge(timeLog);
            if (projectOld != null && !projectOld.equals(projectNew)) {
                projectOld.getTimeLogCollection().remove(timeLog);
                projectOld = em.merge(projectOld);
            }
            if (projectNew != null && !projectNew.equals(projectOld)) {
                projectNew.getTimeLogCollection().add(timeLog);
                projectNew = em.merge(projectNew);
            }
            if (emplyeeOld != null && !emplyeeOld.equals(emplyeeNew)) {
                emplyeeOld.getTimeLogCollection().remove(timeLog);
                emplyeeOld = em.merge(emplyeeOld);
            }
            if (emplyeeNew != null && !emplyeeNew.equals(emplyeeOld)) {
                emplyeeNew.getTimeLogCollection().add(timeLog);
                emplyeeNew = em.merge(emplyeeNew);
            }
            if (createdByOld != null && !createdByOld.equals(createdByNew)) {
                createdByOld.getTimeLogCollection().remove(timeLog);
                createdByOld = em.merge(createdByOld);
            }
            if (createdByNew != null && !createdByNew.equals(createdByOld)) {
                createdByNew.getTimeLogCollection().add(timeLog);
                createdByNew = em.merge(createdByNew);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = timeLog.getTlId();
                if (findTimeLog(id) == null) {
                    throw new NonexistentEntityException("The timeLog with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            TimeLog timeLog;
            try {
                timeLog = em.getReference(TimeLog.class, id);
                timeLog.getTlId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The timeLog with id " + id + " no longer exists.", enfe);
            }
            Projects project = timeLog.getProject();
            if (project != null) {
                project.getTimeLogCollection().remove(timeLog);
                project = em.merge(project);
            }
            Employees emplyee = timeLog.getEmplyee();
            if (emplyee != null) {
                emplyee.getTimeLogCollection().remove(timeLog);
                emplyee = em.merge(emplyee);
            }
            Employees createdBy = timeLog.getCreatedBy();
            if (createdBy != null) {
                createdBy.getTimeLogCollection().remove(timeLog);
                createdBy = em.merge(createdBy);
            }
            em.remove(timeLog);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<TimeLog> findTimeLogEntities() {
        return findTimeLogEntities(true, -1, -1);
    }

    public List<TimeLog> findTimeLogEntities(int maxResults, int firstResult) {
        return findTimeLogEntities(false, maxResults, firstResult);
    }

    private List<TimeLog> findTimeLogEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(TimeLog.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public TimeLog findTimeLog(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(TimeLog.class, id);
        } finally {
            em.close();
        }
    }

    public int getTimeLogCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<TimeLog> rt = cq.from(TimeLog.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
